import * as echarts from 'echarts';
import { ipcRenderer } from 'electron';

type ChartDataGroup = number[];
let chartInstance: echarts.ECharts | null = null;
export async function loadData(experimentName:string): Promise<void> {

    const parsedfileName = `parsed_data_${experimentName}.txt`;

  try{
    const result = await ipcRenderer.invoke('read-file',parsedfileName);
    const lines = result.data.split("\n");//​​.filter(Boolean); // 去除空行
    const groupData: ChartDataGroup[] = [[],[],[],[],[],[]];

    for(let i=0; i<lines.length; i += 6){
        groupData[0].push(lines[i])
        groupData[1].push(lines[i+1])
        groupData[2].push(lines[i+2])
        groupData[3].push(lines[i+3])
        groupData[4].push(lines[i+4])
        groupData[5].push(lines[i+5])
       
    }
    drawStackedChart(groupData);
  }catch(error){
    console.error("读取文件失败:", error);
  }
}

export  function drawStackedChart(data:ChartDataGroup[]):void{
  const chartDom = document.getElementById('chart');
  if(!chartDom){
    console.error("未找到chart元素");
     return;
    }
  if(chartInstance){
    chartInstance.dispose();
  }

  // 初始化新图表
  chartInstance = echarts.init(chartDom);


  const seriesName = ['通道1', '通道2', '通道3', '通道4', '通道5', '通道6'];
  const seriesData: number[][] = data;

  // data.forEach(group => {
  //   group.forEach((value, index) => {
  //     seriesData[index].push(value);
  //   });
  // });

  const option:echarts.EChartsOption ={
    title:{

    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: seriesName
    },
    xAxis:{
      type: 'category',
      name: '组数',
      data: data.map((_, index) => `${index + 1}`)
    },
    yAxis:{
      type: 'value',
      name: '数据值'
    },
    series:[
      {
        name: seriesName[0],
        type: 'line',
        data: seriesData[0]
      },
      {
        name: seriesName[1],
        type: 'line',
        data: seriesData[1]
      },
      {
        name: seriesName[2],
        type: 'line',
        data: seriesData[2] 
      },
      {
        name: seriesName[3],
        type: 'line',
        data: seriesData[3]
      },
      {
        name: seriesName[4],
        type: 'line',
        data: seriesData[4]
      },
      {
        name: seriesName[5],
        type: 'line',
        data: seriesData[5]
        
      }
    ],
    dataZoom: [
    {
      type: 'slider', // 滑块型数据区域缩放组件
      start: 0,       // 数据窗口范围的起始百分比（0%~100%）
      end: 100         // 数据窗口范围的结束百分比
    }
  ]

  };

  chartInstance.setOption(option);

}
  